import 'dart:convert';

import 'package:chi_med_det_flutter/answer_list.dart';
import 'package:chi_med_det_flutter/url.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;

class Archive extends StatefulWidget {
  const Archive({super.key});

  @override
  State<StatefulWidget> createState() => _ArchiveState();
}

class _ArchiveState extends State<Archive> {
  String _diagnosis = '';
  final List<dynamic> _suggestion = [];

  final List<Tab> tabs = <Tab>[
    Tab(child: Text("诊断", style: TextStyle(fontSize: 20))),
    Tab(child: Text("建议", style: TextStyle(fontSize: 20))),
  ];

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    AnswerList answerList = Provider.of<AnswerList>(context);
    List<Answer> answers = answerList.getAnswerList();
    List<Map<String, dynamic>> answerMaps = [];
    for (int i = 0; i < answers.length; i++) {
      answerMaps.add(answers[i].toMap());
    }
    requestDetResult(answerMaps);
  }

  void requestDetResult(List<Map<String, dynamic>> answerMaps) async {
    final url = Uri.parse(URL.GET_DET_RESULT);
    final response = await http.post(
      url,
      headers: const {'Content-Type': 'application/json'},
      body: jsonEncode({'answerList': answerMaps}),
    );
    Map<String, dynamic> res = jsonDecode(response.body);
    if (response.statusCode == 200) {
      final detResult = res['detResult'];
      if (detResult is Map) {
        if (detResult['diagnosis'] is String) {
          setState(() {
            _diagnosis = detResult['diagnosis'];
          });
        }
        if (detResult['suggestion'] is List) {
          _suggestion.addAll(detResult['suggestion']);
        }
      }
    }
  }

  ListView makeSuggestionList() {
    List<Widget> items = [];
    for (var value in _suggestion) {
      items.add(
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(value.toString(), style: TextStyle(fontSize: 18)),
            SizedBox(height: 10,),
          ],
        )
      );
    }
    return ListView(children: items);
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: DefaultTabController(
        length: tabs.length,
        child: Column(
          children: [
            TabBar(tabs: tabs),
            Expanded(
              child: TabBarView(
                children: [
                    Container(
                      padding: EdgeInsets.all(20),
                      alignment: Alignment.topLeft,
                      child: Text(_diagnosis, style: TextStyle(fontSize: 18)),
                    ),
                  Padding(
                    padding: EdgeInsets.all(20),
                    child: Column(
                      children: [Expanded(child: makeSuggestionList())],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
